home *** CD-ROM | disk | FTP | other *** search
/ ftp.cs.arizona.edu / ftp.cs.arizona.edu.tar / ftp.cs.arizona.edu / icon / newsgrp / group98c.txt / 000127_icon-group-sender _Thu Dec 10 17:13:11 1998.msg < prev    next >
Internet Message Format  |  2000-09-20  |  2KB

  1. Return-Path: <icon-group-sender>
  2. Received: (from root@localhost)
  3.     by baskerville.CS.Arizona.EDU (8.9.1a/8.9.1) id RAA07960
  4.     for icon-group-addresses; Thu, 10 Dec 1998 17:13:00 -0700 (MST)
  5. Message-Id: <199812110013.RAA07960@baskerville.CS.Arizona.EDU>
  6. Date: Thu, 10 Dec 1998 10:44:01 -0700
  7. From: Gregg Townsend <gmt>
  8. To: evans.nospam@gte.net, icon-group
  9. Subject: Re:  Formatting Reals
  10. Errors-To: icon-group-errors@optima.CS.Arizona.EDU
  11. Status: RO
  12.  
  13. I use the code below for formatting real numbers into fixed-width
  14. fields.  It's not as general as C's printf, and it's interpreted,
  15. but it works.
  16.  
  17. (And to answer another question:  real numbers are implemented by
  18.  C's "double" datatype.)
  19.  
  20.    ---------------------------------------------------------------------------
  21.    Gregg Townsend              Gould-Simpson Building   gmt@cs.arizona.edu
  22.    Staff Scientist             1040 E. 4th St.          32 13 45N  110 57 16W
  23.    Dept. of Computer Science   PO Box 210077            tel: +1 520 621 4325
  24.    The University of Arizona   Tucson, AZ  85721-0077   fax: +1 520 621 4246
  25.  
  26. ==============================================================================
  27.  
  28.  
  29. procedure main()            #: sample driver
  30.    every write(frn(&pi, 20, 0 to 16))
  31. end
  32.  
  33.  
  34. #    frn(r, w, d)    format real number r into a string with d digits
  35. #            after the decimal point; a result narrower than w
  36. #            characters is padded on the left with spaces.
  37. #            Fixed format is always used; there is no exponential
  38. #            notation. 
  39. #
  40. #            Defaults:  w=0, d=0
  41.  
  42. $define MAXDECIMALS 25
  43.  
  44. procedure frn(r, w, d)        #: format real number
  45.  
  46.    local s
  47.    static mlist
  48.    initial every put(mlist := list(), 10.0 ^ (0 to MAXDECIMALS))
  49.  
  50.    r := real(r) | runerr(102, r)
  51.    (/d := 0) | (d >:= MAXDECIMALS)
  52.    if r >= 0.0 then {
  53.       s := string(integer(r * mlist[d + 1] + 0.5))
  54.       s := right(s, *s < d + 1, "0")
  55.       }
  56.    else {
  57.       s := string(integer(-r * mlist[d + 1] + 0.5))
  58.       s := right(s, *s < d + 1, "0")
  59.       s := "-" || s
  60.       }
  61.    s := right(s, *s < (\w - 1))
  62.  
  63.    return s ? (tab(-d) || "." || tab(0))
  64.  
  65. end
  66.